#!/bin/bash

# override with -s
site=blackarch.org
# override with -u
user=$USER

while (( $# )) ; do
	case "$1" in
		-s)
			site=$2
			shift
			;;
		-u)
			user=$2
			shift
			;;
		*)
			notify_list+=("$1")
			;;
	esac
	shift
done

remote_irc_notify() {
	b=''

	list_len=3
	use_list=false

	user=$USER
	case "$user" in
		para) user=paraxor ;;
    noptrix) user=noptrix ;;
    nop) user=noptrix ;;
	esac

	hook_file=/etc/barelease_notifico
	hook_url=$(cat $hook_file)

	packages=("$@")

	if (( ${#packages[@]} != 1 )) ; then
		s=s
	fi

	discord_notify() {
		webhook_file="/etc/discord_webhook"
		webhook_url="$(cat ${webhook_file})"

    x="$(echo ${1} | sed 's/\x02//g')"
    curl "${webhook_url}" \
      -s \
			-X 'POST' \
			-H 'Content-Type: application/json' \
      -d "{\"username\": \"Bitch Talker\", \"embeds\": [{\"description\": \"${x}\", \"color\": 15258703}]}"
	}

	url_encode() {
		xxd -plain | tr -d '\n' | sed 's/\(..\)/%\1/g'
	}

	send_payload() {
		curl -s "$hook_url" -d "payload=$(printf %s "$1" | url_encode)"

		# discord webhook only
		discord_notify "${1}"
	}

	# TODO: group packages by name
	sprunge=$(printf '%s\n' "${packages[@]}" | curl -s -X POST --data-binary @- https://paste.rs/)
	#sprunge=$(printf '%s\n' "${packages[@]}" | curl -s -F 'clbin=<-' https://clbin.com/)
	#sprunge=$(printf '%s\n' "${packages[@]}" | curl -s -F'file=@-' https://0x0.st)
	#sprunge=$(printf '%s\n' "${packages[@]}" | nc -w 3 termbin.com 9999 2>/dev/null)

	# TODO: color?
	if $use_list ; then
		send_payload "$b$user$b pushed ${#packages[@]} backd00r$s to the bin repo, including:"
	else
		send_payload "$b$user$b pushed ${#packages[@]} backd00r$s to the bin repo: $sprunge"
	fi

	if $use_list ; then
		for p in ${packages[@]:0:$list_len} ; do
			send_payload "- $p"
		done

		if (( ${#packages[@]} > $list_len )) ; then
			send_payload "full list: $sprunge"
		fi
	fi
}

ssh -l "$user" "$site" "$(declare -f remote_irc_notify); remote_irc_notify ${notify_list[@]}"

